package com.thinkgem.jeesite.common.servlet;

import java.io.*;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.thinkgem.jeesite.common.utils.FileUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.util.UriUtils;

import com.thinkgem.jeesite.common.config.Global;

/**
 * 查看CK上传的图片
 * @author ThinkGem
 * @version 2014-06-25
 */
public class UserfilesDownloadServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;
	private Logger logger = LoggerFactory.getLogger(getClass());

//	public void fileOutputStream(HttpServletRequest req, HttpServletResponse resp)
//			throws ServletException, IOException {
//		String filepath = req.getRequestURI();
//		int index = filepath.indexOf(Global.USERFILES_BASE_URL);
//		if(index >= 0) {
//			filepath = filepath.substring(index + Global.USERFILES_BASE_URL.length());
//		}
//		try {
//			filepath = UriUtils.decode(filepath, "UTF-8");
//		} catch (UnsupportedEncodingException e1) {
//			logger.error(String.format("解释文件路径失败，URL地址为%s", filepath), e1);
//		}
//		File file = new File(Global.getUserfilesBaseDir() + Global.USERFILES_BASE_URL + filepath);
//		try {
//			FileCopyUtils.copy(new FileInputStream(file), resp.getOutputStream());
//			resp.setHeader("Content-Type", "application/octet-stream");
//			return;
//		} catch (FileNotFoundException e) {
//			req.setAttribute("exception", new FileNotFoundException("请求的文件不存在"));
//			req.getRequestDispatcher("/WEB-INF/views/error/404.jsp").forward(req, resp);
//		}
//	}
public void fileOutputStream(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException{
    String filepath = req.getRequestURI();
    		int index = filepath.indexOf(Global.USERFILES_BASE_URL);
		if(index >= 0) {
			filepath = filepath.substring(index + Global.USERFILES_BASE_URL.length());
		}
		try {
			filepath = UriUtils.decode(filepath, "UTF-8");
		} catch (UnsupportedEncodingException e1) {
			logger.error(String.format("解释文件路径失败，URL地址为%s", filepath), e1);
		}
		File downloadFile = new File(Global.getUserfilesBaseDir() + Global.USERFILES_BASE_URL + filepath);
    long pos = FileUtil.headerSetting(downloadFile, req, resp);
    //      log.info("跳过"+pos);
    ServletOutputStream os = null;
    BufferedOutputStream out = null;
    RandomAccessFile raf = null;
    byte b[] = new byte[1024];//暂存容器
    try {
        os = resp.getOutputStream();
        out = new BufferedOutputStream(os);
        raf = new RandomAccessFile(downloadFile, "r");
        raf.seek(pos);
        try {
            int n = 0;
            while ((n = raf.read(b, 0, 1024)) != -1) {
                out.write(b, 0, n);
            }
            out.flush();
        } catch(IOException ie) {
            req.setAttribute("exception", new FileNotFoundException("请求的文件不存在"));
			req.getRequestDispatcher("/WEB-INF/views/error/404.jsp").forward(req, resp);
        }
    } catch (Exception e) {
        req.setAttribute("exception", new FileNotFoundException("请求的文件不存在"));
            req.getRequestDispatcher("/WEB-INF/views/error/404.jsp").forward(req, resp);
    } finally {
        if (out != null) {
            try {
                out.close();
            } catch (IOException e) {
                req.setAttribute("exception", new FileNotFoundException("请求的文件不存在"));
			req.getRequestDispatcher("/WEB-INF/views/error/404.jsp").forward(req, resp);
            }
        }
        if (raf != null) {
            try {
                raf.close();
            } catch (IOException e) {
                req.setAttribute("exception", new FileNotFoundException("请求的文件不存在"));
			req.getRequestDispatcher("/WEB-INF/views/error/404.jsp").forward(req, resp);
            }
        }
    }
}
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		fileOutputStream(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		fileOutputStream(req, resp);
	}
}
